package com.project_test.kun.travelling_1st.Butler;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Cache;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.project_test.kun.travelling_1st.R;
import com.project_test.kun.travelling_1st.Utils.CustomVolley;
import com.project_test.kun.travelling_1st.beans.GlobalCity;
import com.project_test.kun.travelling_1st.toolActivity.CityChooseActivity;

import org.json.JSONObject;

import java.util.List;

public class ButlerActivity extends AppCompatActivity implements View.OnClickListener {
    private PullToRefreshListView pullList;
    private ImageView back;
    private TextView place_text;
    private RequestQueue mRequestQueue;
    private Butler butler;
    private RelativeLayout layout;
    private List<Butler.DataBean.ListBean> data;
    private String PATH="http://www.handybest.com/index.php?m=api&c=Keeper&a=keeperList&page=";
    private int page=1;
    private String PATH2="&cityid=";
    private String PATH3="&device_token=864394010925172&push_token=363646a50016412a414f89bae67b47cd972d5bd5&mobile_type=Android&mobile_model=GT-N7100%2C4.4.2&version_code=10000";
    private ButlerAdapter adapter;
    private JSONObject json;
    private String detail_path1="http://www.handybest.com/index.php?m=api&c=Keeper&a=detail&kid=";
    private String detail_path2="&device_token=864394010925172&push_token=48c3e0cad9df6d2e4446b318711cdb7e09784448" +
            "&mobile_type=Android&mobile_model=GT-N7100%2C4.4.2&version_code=10000";

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==1){
                json = (JSONObject) msg.obj;
                Gson gson=new Gson();
                butler = gson.fromJson(json.toString(), Butler.class);
                data= butler.getData().getList();
                adapter=new ButlerAdapter(data,ButlerActivity.this);
                pullList.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                if (pullList.isRefreshing()) {
                    pullList.onRefreshComplete();
                }}
            if (msg.what==2){
                pullList.onRefreshComplete();

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_butler);
        initView();
        initData();
        String path = PATH + page + PATH2+ GlobalCity.getInstance().getGlobalCityId()+PATH3;
        jsonRequest(path);
       pullList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
           @Override
           public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
               ConnectivityManager systemService = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
               NetworkInfo info = systemService.getActiveNetworkInfo();
               if (info == null || !systemService.getBackgroundDataSetting()){
                   handler.sendEmptyMessageDelayed(2,500);
               }else{
                   String path = PATH + page + PATH2+ GlobalCity.getInstance().getGlobalCityId()+PATH3;
                   jsonRequest(path);
               }
           }

           @Override
           public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
               ConnectivityManager systemService = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
               NetworkInfo info = systemService.getActiveNetworkInfo();
               if (info == null || !systemService.getBackgroundDataSetting()) {
                   handler.sendEmptyMessageDelayed(3, 500);
               } else {
                   page+=1;
                   String path = PATH + page + PATH2 + GlobalCity.getInstance().getGlobalCityId() + PATH3;
                   jsonRequest(path);

               }
           }
       });

        pullList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String keyId=data.get(i-1).getId();
                String detailPath=detail_path1+keyId+detail_path2;
                Intent intent=new Intent(ButlerActivity.this,ButlerDetailActivity.class);
                intent.putExtra("detailPath",detailPath);
                startActivity(intent);
            }
        });
    }

    private void initData() {
        back.setClickable(true);
        back.setOnClickListener(this);

        layout.setClickable(true);
        layout.setOnClickListener(this);
    }

    private void initView() {
        back= (ImageView) findViewById(R.id.goBack);
        place_text= (TextView) findViewById(R.id.place_text);
        layout=new RelativeLayout(getApplicationContext());
        layout= (RelativeLayout) findViewById(R.id.place_layout);
        pullList= (PullToRefreshListView) findViewById(R.id.butler_listView);
    }

    private void jsonRequest(final String path) {
        mRequestQueue = CustomVolley.getInstance(this).sRequestQueue;
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(JsonObjectRequest.Method.GET,
                path, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Message msg = new Message();
                msg.what=1;
                msg.obj = response;
                handler.sendMessage(msg);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //            获取缓存
                Cache cache = mRequestQueue.getCache();
                if (cache != null) {
                    Cache.Entry entry = cache.get(path);
                    if (entry != null) {
                        byte[] data = entry.data;
                        if (data != null) {
                            try {
                                String result = new String(data, "UTF-8");
                                JSONObject obj = new JSONObject(result);
                                Message msg = new Message();
                                msg.what=1;
                                msg.obj = obj;
                                handler.sendMessage(msg);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        });
        mRequestQueue.add(jsonObjectRequest);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.goBack:
                //TODO:跳转回上一页面
                finish();
                break;
            case R.id.place_layout:
                //TODO:跳转到城市选择
                Intent intent=new Intent(this,CityChooseActivity.class);
                startActivity(intent);
                break;
        }
    }

     @Override
    protected void onResume() {
        super.onResume();
        place_text.setText(GlobalCity.getInstance().getGlobalCityName());
         if (data!=null) {
             data.clear();
         }
        String url= PATH+page+PATH2+ GlobalCity.getInstance().getGlobalCityId()+PATH3;
        jsonRequest(url);
        pullList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String vid = data.get(position-1).getId();
                Intent intent=new Intent(ButlerActivity.this,ButlerDetailActivity.class);
                intent.putExtra("vid",vid);
                startActivity(intent);
            }
        });

    }
}
